/* $RCSFile: EntityList.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/CRMWrapper3/EntityList.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:32  christian.surieux
 *   Added Log to All cs files
 */

// =======================================================================
//  File: EntityList.cs
// =======================================================================
//  This file is part of Addon Nice product.
//  Copyright (C) Addon Nice.  All rights reserved.
// =======================================================================

using System;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using CrmSdk;
using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper;

namespace AddonNice.CRMWrapper
{
	/// <summary>
	/// Build a list of all entities and allow acces to each one
	/// by easy accessor like this[entityName] 
	public class EntityList
	{
        /*
        public static string[] excludedEntities = new string[] {
												"attributemap", "bulkimport", "businessunitmap",
												"commitment", "displaystringmap", "documentindex",
												"entitymap", "importconfig", "integrationstatus",
												"internaladdress", "privilegeobjecttypecodes", 
												"roletemplate", "roletemplateprivileges", 
												"statusmap", "stringmap", "stringmapbit" };
        */
        SortedList<string,EntityConfig> _entityList	=	new SortedList<string,EntityConfig>();
		/// <summary>
		/// SortedList containing EntityConfig objects
		/// </summary>
		public SortedList<string,EntityConfig> entitiesTable
		{
			get
			{
				return _entityList;
			}
		}

        private bool _isAdmin =	false;
		protected bool isAdmin
		{
			get
			{
				return _isAdmin;
			}
		}
        private EntityInternalItems _Flags =    EntityInternalItems.EntityOnly;
		protected EntityInternalItems Flags 
		{
			get
			{
				return _Flags;
			}
		}

        private CRMWrapperBase _wrapper =	null;
		protected CRMWrapperBase wrapper
		{
			get
			{
				return _wrapper;
			}
		}
        /*
        public static Hashtable excludedEntitiesHashtable
        {
            get
            {
                if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine("[V]EntityList excludedEntities.",CRMTraceSwitch.Sw.Info);
                Hashtable _excludedEntityTable = new Hashtable();
                for (int n = 0; n < excludedEntities.Length; n++)
                    _excludedEntityTable.Add(excludedEntities[n].GetHashCode(), excludedEntities[n]);
                return _excludedEntityTable;
            }
        }
        */
		/// <summary>
		/// Build a list of all entities and allow access to each one
		/// by easy accessor like this[entityName] 
        /// Flags default to EntityInternalItems.EntityOnly
		/// </summary>
		public EntityList(CRMWrapperBase w,bool isAdm)
        {            
			_wrapper			=	w;
			_isAdmin			=	isAdm;

            // Add all entities in the system to the array
            BuildEntitiesList(true,false);
        }

        public EntityList(CRMWrapperBase w,EntityInternalItems f,bool isAdm,bool allEntities)
        {            
			_wrapper			=	w;
			_isAdmin			=	isAdm;
            _Flags              =   f;

            // Add all entities in the system to the array
            BuildEntitiesList(allEntities,false);
        }
 
        public EntityList(CRMWrapperBase w,EntityInternalItems f,bool CustomOnly,bool isAdm,bool allEntities)
        {            
			_wrapper			=	w;
			_isAdmin			=	isAdm;
            _Flags              =   f;

            // Add all entities in the system to the array
            BuildEntitiesList(allEntities,CustomOnly);
        }
 
        /// <summary>
        /// This adds all entities in the system (supported and custom)
        /// Or a selection of 'traditionnal' entities depending of version
        /// </summary>
        private void BuildEntitiesList(bool allEntities,bool CustomOnly)
        {
            if (allEntities)
                MetadataCache.BuildEntitiesList(wrapper, Flags, isAdmin,CustomOnly, ref _entityList, delegate(string s,string dn) { AddEntityToList(s); });
            else
            {
                List<string> lst    =   wrapper.GetEntityList();
                foreach(string ent in lst)
                    AddEntityToList(ent);
            }
        }

        /// <summary>
        /// Adds the specified entity to the list with the proper display name
        /// </summary>
        private void AddEntityToList(string entityName)
        {
			if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntityList AddEntityToList entityName: {0}.",entityName),CRMTraceSwitch.Sw.Info);
            // Retrieve entity
            EntityConfig entity     =   new EntityConfig(wrapper,entityName,Flags,isAdmin);
            // Add entity to array 
            _entityList.Add(entityName,entity);
			if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntityList AddEntityToList entityName: {0} Added.",entityName),CRMTraceSwitch.Sw.Info);
        }

		public EntityConfig this[string key]
		{
            get
            {
				if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntityList this[{0}]",key),CRMTraceSwitch.Sw.Info);
                if ( _entityList.ContainsKey(key) )
                    return _entityList[key];
				if ( CRMTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntityList this[{0}] not found",key),CRMTraceSwitch.Sw.Info);
                return null;
            }
            set
            {
                _entityList[key] = value;

            }
        }

        /// <summary>
        /// Return a specialized arraylist with displaynames, typecodes, names as CrmEntityListItem
        /// </summary>
        /// <returns></returns>
        public ArrayList ToArrayList()
        {
			ArrayList	lst     =	new ArrayList();
            foreach (KeyValuePair<string, EntityConfig> kvp in entitiesTable)
            {
                EntityConfig e  =   kvp.Value;
                // avoid empty display names
                if ( e.DisplayName != string.Empty )
                    lst.Add(new CrmEntityListItem(e.DisplayName, e.ObjectTypeCode, e.entityName));
                else if ( e.entityName != string.Empty)
                    lst.Add(new CrmEntityListItem(e.entityName , e.ObjectTypeCode, e.entityName));
            }
			if ( CRMTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EntityList ToArrayList Count:{0}",lst.Count),CRMTraceSwitch.Sw.Info);
			return lst;
        }
    }
}
